var jfRedirectByUserAgent = (function() {
  var userAgent = navigator.userAgent 
  var that = {
    cookieName: 'jfRedirectByUserAgent',
    
    doConditionalRedirect: function(url, userAgentWhitelist, userAgentBlacklist, confirmMessage) {
      if (!that.readSessionConfig('suppressRedirects') && userAgent) {

        for(var i=0; i<userAgentBlacklist.length; i++) {
          var regex = new RegExp(userAgentBlacklist[i], "i");
          if (regex.exec(userAgent)) {
            return false;
          }
        }

        for(var i=0; i<userAgentWhitelist.length; i++) {
          var regex = new RegExp(userAgentWhitelist[i], "i");
          if (regex.exec(userAgent)) {
            if(confirmMessage) {
              var confirmed = that.readSessionConfig('confirmation');
              if (confirmed === null) {
                confirmed = confirm(confirmMessage) ? 1 : 0;
                that.writeSessionConfig('confirmation', confirmed);
              }
              else {
                confirmed = parseInt(confirmed);
              }
              
              if (!confirmed) {
                return false;
              }
            }

            that.writeSessionConfig('referrer', document.referrer ? document.referrer : '')

            window.stop();
            document.location.href=decodeURIComponent(url);
          }
        }
      }      
    },

    suppressRedirectsForSession: function() {
      that.writeSessionConfig('suppressRedirects', 1)
    },
    
    writeSessionConfig: function(key, value) {
      if (window.sessionStorage) {
        window.sessionStorage.setItem(that.cookieName+'_'+key, value);
      }
    },

    readSessionConfig: function(key) {
      if (window.sessionStorage) {
        return window.sessionStorage.getItem(that.cookieName+'_'+key);
      }
    }
  }
  
  return that;
})();
